<?php
require_once( dirname(__FILE__) . '/mysqlstart2.php' );

	define('BAD', 0);
	define('GOOD', 1);
	
	# -------
	# print test result
	function print_test_result( $p_result, $p_hard_fail=true, $p_message='' )
	{
		global $g_failed;
		echo '<td ';
		
		if($p_result == BAD)
		{
			if ($p_hard_fail)
			{
				$g_failed = true;
				echo 'bgcolor="red">BAD';
			}
			else
			{
				echo 'bgcolor="pink">POSSIBLE PROBLEM';
			}
			if ('' != $p_message)
			{
				echo '<br />'.$p_message;
			}
		}

		if(GOOD == $p_result)
		{
			echo 'bgcolor="green">GOOD';
		}
		echo '</td>';
	}
	
	# -------
	# print test header and result
	function print_test( $p_test_description, $p_result, $p_hard_fail=true, $p_message='' )
	{
		echo "\n<tr><td bgcolor=\"#ffffff\">$p_test_description</td>";
		print_test_result( $p_result, $p_hard_fail, $p_message );
		echo "</tr>\n";
	}
	
	# install_state
	#   0 = no checks done
	#   1 = server ok, get database information
	#   2 = install the database
	#   3 = done, link to login or db updater
	if(isset($_POST["install"]))
	{
		$t_install_state = $_POST["install"];
	}
	else
	{
		$t_install_state = 0;
	}

// firsttime install of lifestylelinking //

// mysql database install  (too come)
//$db->query ="CREATE DATABASE `aboyn0_gadgets` " ;
//$resultdb = mysql_query($db->query) or die(mysql_error());
?>

<?php
if($t_install_state == 2)	
{
	# check to see if database table exists already
	$table_exists = false;
	$db->query = "SHOW TABLES LIKE \"siteinfo\"";
	
	if( mysql_num_rows( mysql_query($db->query)))
	{
		$table_exists = true;
	}
	
	if($table_exists == false)
	{
		$db->query ="CREATE TABLE  siteinfo (
			`infoid` int(11) NOT NULL auto_increment,
	  		`type` varchar(100) NOT NULL,
	  		`siteinfo` varchar(255) NOT NULL,
			PRIMARY KEY  (`infoid`)
			) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ";

		//echo $db->query;
		$resultinfo = mysql_query($db->query) or die(mysql_error());
	

		// has the baseurl been set?
		// query db to find base folder url
		$db->query ="SELECT * FROM ".RSSDATA.".siteinfo";
		//echo $db->query;
		$resultsetf = mysql_query($db->query) or die(mysql_error());

		if (mysql_num_rows($resultsetf)  > 0 )  {
			//echo 'zero';

			while ($row = mysql_fetch_object($resultsetf))  {
				$siteinfo[$row->type] = $row->siteinfo;
			} 
			//print_r($siteinfo);
			$basefolderurl = $siteinfo[baseurl];
			$abspath = $siteinfo[absolpath];

			define( 'LLFOLDER', $basefolderurl );
			define( 'ABSPATH', $abspath );
		}  // closes if
		else 
		{
			//echo 'else';
			// need to find out url path
			$host = 'http://'.$_SERVER[HTTP_HOST];
			$controlleruri = $_SERVER[REQUEST_URI];

			// tidy to find start folder depth
			$starturl = substr($controlleruri,0,(strLen($controlleruri)-11));
			$baseurl = $starturl;
			//$baseurl = $controlleruri;

			$abspath = $_SERVER[DOCUMENT_ROOT].$baseurl;

			$startinfo[host] = $host;
			$startinfo[baseurl] = $baseurl;
			$startinfo[absolpath] = $abspath;

			$db->query =" INSERT INTO ".RSSDATA.".siteinfo (type, siteinfo) VALUES ";

			foreach ($startinfo as $type=>$sinfo)  {
				$db->query .= "( '$type', '$sinfo' ),";
			}  // closes foreach

			$db->query=substr($db->query,0,(strLen($db->query)-1));

			$resultbaseurl = mysql_query($db->query) or die(mysql_error());

			define( 'LLFOLDER', $baseurl );
			define( 'ABSPATH',  $abspath);
		} // closes else

		// setting up all the database tables, tables and words
		function tablesetup ()
		{
			set_time_limit(0);

			$tables = dirname(__FILE__) . '/lifestyletables.sql';
			$tablesb = dirname(__FILE__) . '/words.sql';

			$tablesarr[] = $tables;
			$tablesarr[] = $tablesb;

			foreach ($tablesarr as $tabsql)
			{
				$arr_sql = '';
				// setting up all the database tables, tables and words
				$tablesstart = file_get_contents($tabsql, true);

				$arr_sql =  preg_split('/;[\n\r]+/', $tablesstart);

	  			foreach ($arr_sql as $ars=>$sql) 
	  			{
	  				if (strlen($sql) > 5 ) 
	    			{
	    				$db->query ="$sql";
	    				//echo $db->query;
	    				$resultbaseurl = mysql_query($db->query) or die(mysql_error());
    
	    			} // closes if 

	  			}  // closes foreach
			}  // closes foreach
		}  // closes function

		tablesetup ();
	}

	function valid_email($str)
	{
		return ( ! preg_match("/^([a-z0-9\+_\-]+)(\.[a-z0-9\+_\-]+)*@([a-z0-9\-]+\.)+[a-z]{2,6}$/ix", $str)) ? FALSE : TRUE;
	}
	
	function checkUnique($field, $compared)
	{
		$query = mysql_query("SELECT `".mysql_real_escape_string($field)."` FROM `users` WHERE `".mysql_real_escape_string($field)."` = '".mysql_real_escape_string($compared)."'");
		if(mysql_num_rows($query)==0)
		{
			return TRUE;
		}
		else {
			return FALSE;
		}
	}
	  
	function numeric($str)
	{
		return ( ! ereg("^[0-9\.]+$", $str)) ? FALSE : TRUE;
	}
	
	function alpha_numeric($str)
	{
		return ( ! preg_match("/^([-a-z0-9])+$/i", $str)) ? FALSE : TRUE;
	}
	
	function random_string($type = 'alnum', $len = 8)
	{					
		switch($type)
		{
			case 'alnum'	:
			case 'numeric'	:
			case 'nozero'	:
			
					switch ($type)
					{
						case 'alnum'	:	$pool = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
							break;
						case 'numeric'	:	$pool = '0123456789';
							break;
						case 'nozero'	:	$pool = '123456789';
							break;
					}
	
					$str = '';
					for ($i=0; $i < $len; $i++)
					{
						$str .= substr($pool, mt_rand(0, strlen($pool) -1), 1);
					}
					return $str;
			  break;
			case 'unique' : return md5(uniqid(mt_rand()));
			  break;
		}
	}
  
	//create userprofile url
   $nospacename = $_POST['username'];

   // need to create singleword for user  profileurl
   $createprofileurl = str_replace (" ", "", $nospacename); 

	$error = "There is an error with the registration data.<br/>";
	
	// Check Valid username
	if($_POST['username'] == '')
	{
		$error .= "Username cannot be blank<br/>";
		$g_failed = TRUE;
	}
	else
	{ 
		// Check unique username
		if(checkUnique('Username', $_POST['username']) == FALSE)
		{
			$error .= "Username has already been taken<br/>";
			$g_failed = TRUE;
		}
	}
	
	// Check Valid password
	if($_POST['password'] == '')
	{
		$error .= "Password cannot be blank<br/>";
		$g_failed = TRUE;
	}
	
	// Check password matches confirmation password
	if($_POST['password'] != $_POST['password_confirmed'])
	{
		$error .= "Password does not match confirmation password<br/>";
		$g_failed = TRUE;
	}
	
	// Check email
	if($_POST['email'] == '')
	{
		$error .= "Email cannot be blank<br/>";
		$g_failed = TRUE;
	}
	else
	{
		// Check Valid email
		if(valid_email($_POST['email']) == FALSE)
		{
			$error .= "Email address is not valid<br/>";
			$g_failed = TRUE;
		}

		// Check unique email
		if(checkUnique('Email', $_POST['email']) == FALSE)
		{
			$error .= "Email address has already been taken<br/>";
			$g_failed = TRUE;
		}
	}
	
	if($g_failed == FALSE)
	{
		$db->query = "INSERT INTO users (Username , Password, Email, Active, Level_access, Random_key, userprofile) VALUES ('".mysql_real_escape_string($_POST['username'])."', '".mysql_real_escape_string(md5($_POST['password']))."', '".mysql_real_escape_string($_POST['email'])."', '1', '3', '".random_string('alnum', 32)."', '$createprofileurl') ";
    
    	$resultbaseurl = mysql_query($db->query) or die(mysql_error());
	}  // closes if		
		
	if(false == $g_failed)
	{
		$t_install_state++;
		$error = "";
	}
	else
	{
		$t_install_state--;	# a check failed, redisplay the questions
	}
	
}  // closes if installed pressed # end install_state = 2
?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
	
	<html xmlns="http://www.w3.org/1999/xhtml" >
	<head>
	   <meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
		
		<title>open - lifestyle linking</title>
		<meta name="description" content="Main Page" />
		<meta name="page-topic" content="Homepage" />

		
		<meta name="robots" content="all" />
		<meta name="author" content="" />
		<meta name="author" content="" />
		<meta name="Keywords" content="" /> 	
		
		<!--Main Style Sheet-->
		<!--session selector to pick which stylesheet based on context if this header is in a php function-->
<style>

#container 
{
    margin: auto;
/*    min-width: 800px;*/
    width: 940px;
    
    padding: 0.5em;    
    background-color: #ffffff;
}

</style>
	
	
<body>

	<div id="container"> <!--is closed in footer.php-->
		<h1>lifestylelinking Installation</h1>
		<p>Welcome to the lifesylelinking auto install.</p>
		
		<h2>
		<?php
			switch ( $t_install_state )
			{
				case 3:
					echo "Installation Complete";
					break;
						
				case 2:
					echo "Install Database";
					break;
			
				case 1:
					echo "Account Details";
					break;
			
				case 0:
				default:
					echo "Pre-Installation Check";
					break;
			}
		?>
	</h2>
	
	 <div>
		<p><?php if(isset($error)){ echo $error;}?></p>
		<p><?php if(isset($msg)){ echo $msg;}  ?></p>
	</div>

<?php
if ( 0 == $t_install_state )
{
?>
<table width="100%" bgcolor="#222222" border="0" cellpadding="10" cellspacing="1">
<tr>
	<td bgcolor="#e8e8e8" colspan="2">
		<span class="title">Checking Installation...</span>
	</td>
</tr>

<!-- Check PHP Version -->
<tr>
	<td bgcolor="#ffffff">Checking PHP version (your version is <?php echo phpversion(); ?>)</td>
	<?php
		if (phpversion() == '5.2.13')
		{
			print_test_result( GOOD );
		} else
		{
			if(function_exists ('version_compare'))
			{
				if(version_compare(phpversion(), '5.2.13', '>=' ))
				{
					print_test_result(GOOD);
				}
				else
				{
					print_test_result(BAD, true, 'Upgrade to a more recent version of PHP');
				}
			}
			else
			{
			 	print_test_result(BAD, true, 'Upgrade to a more recent version of PHP');
			}
		}
	?>
</tr>

<!-- Check Safe Mode -->
<?php
	print_test( 'Checking if safe mode is enabled for install script',
		! ini_get ( 'SAFE_MODE' ),
		true,
		'Disable safe_mode in php.ini before proceeding' )
?>

<!-- display database version -->
<tr>
	<td bgcolor="#ffffff">Checking Database Server Version<br>
		<?php
		
		//echo "Hostname:$f_hostname<br>Username:$f_db_username<br>Password:$f_db_password<br>";
		mysql_connect(DB_HOST, DB_USER, DB_PASSWORD) or die('Could not connect: ' . mysql_error());
		$a = mysql_get_server_info();
		$t_version_info = substr($a, 0, strpos($a, "-"));
		if($t_version_info == '')
		{
			$t_version_info = substr($a, 0, strpos($a, "."));
		}
		echo "Version:$a<br>";
		?>
	</td>
	<?php
		$t_warning = '';
		$t_error = '';
		
				if(function_exists('version_compare'))
				{
					if(version_compare($t_version_info , '4.0.0', '<'))
					{
						$t_error = 'Requires MySQL version 4.0.0 or greater. Current is '.$t_version_info;
					}
				}
							
		print_test_result(('' == $t_error) && ('' == $t_warning), ('' != $t_error), $t_error . ' ' . $t_warning);
	?>
</tr>


</table>

<p>
	<b>Note:</b> The creation of the database tables and data may take a while.
</p>

<?php
	if( false == $g_failed )
	{
		$t_install_state++;
	}
} # end install_state == 0
?>

<?php
# system checks have passed, get the database information
if(1 == $t_install_state)
{
?>

<p>Set the Administrator Control Panel Username and Password:</p>
<br /> 
<form method="post">
	<input name="install" type="hidden" value="2"></input>
  <table>
	<tr>
  <td>Username:</td>
  <td><input type="text" id="username" name="username" size="32" value="<?php if(isset($_POST['username'])){echo $_POST['username'];}?>" /></td>
	</tr>
  <tr>
  <td>Password:</td>
  <td><input type="password" id="password" name="password" size="32" value="" /></td>
	</tr>
   <tr>
   <td>Re-password:</td>
   <td><input type="password" id="password_confirmed" name="password_confirmed" size="32" value="" /></td>
	 </tr>
   <tr>
   <td>Email:</td>
   <td><input type="text" id="email" name="email" size="32" value="<?php if(isset($_POST['email'])){echo $_POST['email'];}?>" /><td>
	</tr>
  <tr>
  <td> </td>
  <td><input type="submit" name="register" value="register" /></td>
  </tr>
 </table>
</form>  

<?php

} # end install_state = 1
?>


<?php
if($t_install_state == 3)	
{
	 echo 'Go to '?><a href="<?php echo LLFOLDER ?>controlpanel/login/login.php">Control Panel Login</a><?php
}
?>
  
</div>  <!-- closes container -->

</body>

</html> 